import React from 'react';
import {
  StyleSheet, Text, View, ListView, Image, AlertIOS,
  TextInput, Modal, Dimensions, ActivityIndicator
} from 'react-native'

//第三方组件
import Icon from 'react-native-vector-icons/Ionicons'
import Button from 'react-native-button'

//自定义组件
import _styles from '../common/styles'
import request from '../common/request'
import config from '../common/config'

let width = Dimensions.get('window').width;  //获取屏幕的宽度

//缓存整个评论列表的数据
let cachedResults = {
  nextpage: 1,  //下一页
  items: [], //列表数据
  total: 0  //总记录条数
};

/***********
 * 视频评论列表
 * 创建时间：2017-2-19
 * 创建人：lcw
 */
const Comments = React.createClass({

  getInitialState() {
    let data = this.props.data;
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      _id: data._id, //评论的视频ID
      dataSource: ds.cloneWithRows([]),  //默认列表为空数据
      isLodingTail: false,  //是否正在获取数据，默认false
      showCommitModal: false, //显示评论窗口
      content: '',  //评论内容，
      isSending: false, //评论请求发送中
    };
  },

  //一般情况下，会在该事件中进行页面初始化数据的异常请求
  componentDidMount(){
    cachedResults.nextpage = 1;
    cachedResults.items = [];
    cachedResults.total = 0;

    this._fetchData(1);
  },

  //首次获取列表数据
  _fetchData(page){
    this.setState({isLodingTail: true});  //打开标记，开始加载请求数据
    request.get(config.api.base + config.api.comments, {accessToken: 'abc', creation: this.state._id})
      .then((data) => {
        if (data && data.success) {  //请求成功
          let items = cachedResults.items.slice(); //拿到现有已加载的数据
          items = items.concat(data.data);  //拼接新获取到的数据

          cachedResults.items = items;
          cachedResults.total = data.total;
          cachedResults.nextpage += 1;

          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(cachedResults.items)
          });
        }
        this.setState({isLodingTail: false}); //加载数据完成，关闭标记
      });
  },

  //解析评论列表数据
  _renderRow(row){
    return (
      <View key={row._id} style={styles.commentBox}>
        <Image style={styles.replayAvatar} source={{uri: row.replayBy.avatar}}/>
        <View style={styles.infoBox}>
          <Text style={styles.nickname}>{row.replayBy.nickname}</Text>
          <Text style={styles.content}>{row.content}</Text>
        </View>
      </View>
    )
  },

  //是否有更多的列表数据
  _hasData(){
    return cachedResults.total !== cachedResults.items.length;
  },

  //加载更多评论（分页）
  _fetchMoreData(){
    if (!this._hasData() || this.state.isLodingTail) {
      return; //没有更多数据或数据正在加载中，则不处理
    }
    this._fetchData(cachedResults.nextpage); //获取下一页的数据
  },

  //底部加载更多区域逻辑
  _renderFooter(){
    if (this.state.isLodingTail) { //正在加载数据时显示空
      return (<View style={styles.loadingMore}/>)
    }

    if (this._hasData() || cachedResults.total === 0) {  //还有数据，或从未加载过数据，显示加载图标
      return (
        <ActivityIndicator style={styles.loadingMore}/>
      )
    }

    return (
      <View style={styles.loadingMore}><Text style={styles.loadingText}>没有更多了</Text></View>
    )
  },

  //控制评论窗口是否可见
  _commentModal(isVisible){
    this.setState({showCommitModal: isVisible});
  },

  //提交评论内容
  _submitComment(){
    if (this.state.content === '') {
      return AlertIOS.alert('评论内容不能为空');
    }
    if (this.state.isSending) {
      return AlertIOS.alert('评论提交中，请勿重新提交');
    }
    this.setState({isSending: true}, () => {
      let body = {
        content: this.state.content,
        creation: this.state._id
      };

      request.post(config.api.base + config.api.submitComment, body)
        .then((data) => {
          let content = this.state.content;
          if (data && data.success) {  //请求成功
            let items = cachedResults.items.slice(); //拿到现有已加载的数据
            items = [{ //将新评论的内容插入到列表的第一条记录
              _id: 12345,
              content: content,
              replayBy: {
                avatar: 'http://dummyimage.com/128x128/98b885)',
                nickname: '张三'
              }
            }].concat(items);  //拼接新获取到的数据

            cachedResults.items = items;
            cachedResults.total = cachedResults.total + 1;  //这里会造成一个小bug，设置后后台的模拟数据20条不能控制了，但正式数据不受影响

            this.setState({
              content: '',
              dataSource: this.state.dataSource.cloneWithRows(cachedResults.items)
            });
            this._commentModal(false); //关闭评论窗口
          }
          this.setState({isSending: false}); //设置请求标记，请求完成
        });
    });

  },

  //评论列表的头部信息区域
  _renderHeader() {
    let data = this.props.data;
    return (
      <View style={styles.headContainer}>
        <View style={styles.authorBox}>
          <Image style={styles.avatar} source={{uri: data.author.avatar}}/>
          <View style={styles.infoBox}>
            <Text style={styles.nickname}>{data.author.nickname}</Text>
            <Text style={styles.title}>{data.title}</Text>
          </View>
        </View>
        <TextInput placeholder='敢不敢评论一下' multiline={true} style={styles.commentInput}
                   onFocus={()=>this._commentModal(true)}/>
        <View style={styles.commentTitle}>
          <Text style={styles.title}>精彩评论</Text>
        </View>
      </View>
    )
  },

  render() {
    return (
      <View style={_styles.container}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          renderHeader={this._renderHeader}
          onEndReached={this._fetchMoreData}
          onEndReachedThreshold={20} //滑动到距离底部触发onEndReached事件的临界值
          renderFooter={this._renderFooter} //页面底部区域内容（加载更多）
          showsVerticalScrollIndicator={false}  //不显示垂直滚动条
          enableEmptySections={true} //为了去掉warn加的代码
          automaticallyAdjustContentInsets={false}  //去掉ListView的头部出现莫名其妙的空白
          removeClippedSubviews={false} //解决listview第一次显示为空白的问题
          style={styles.commentlist}
        />
        <Modal visible={this.state.showCommitModal} animationType={'slide'}
               onRequestClose={()=>this._commentModal(false)}>
          <View style={styles.commitModal}>
            <Icon name='ios-close-outline' size={60} style={styles.closeIcon}
                  onPress={()=>this._commentModal(false)}/>
            <TextInput placeholder='请在这里输入你想说的话....' autoFocus={true}
                       maxLength={300} multiline={true} style={styles.commentContent}
                       onChangeText={(text)=>{  //输入框文本变更时，赋值评论内容
                         this.setState({ content : text })
                       }}
            />
            <Button onPress={this._submitComment} style={_styles.btn}>评论</Button>
          </View>
        </Modal>
      </View>
    )
  }
})

const styles = StyleSheet.create({
  commentlist: {
    paddingHorizontal: 10,
    paddingTop: 10,
  },

  /*作者信息区域样式*/
  authorBox: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30
  },
  infoBox: {
    flex: 1,
    marginLeft: 10
  },
  nickname: {
    fontSize: 18,
  },
  title: {
    marginTop: 6,
    fontSize: 16,
    color: '#666'
  },

  commentInput: {
    height: 60,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    marginBottom: 15,
    fontSize: 16,
    marginTop: 20,
    paddingHorizontal: 5,
  },

  /*视频评论列表样式*/
  commentTitle: {
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    paddingBottom: 6
  },
  commentBox: {
    flexDirection: 'row',
    marginTop: 10,
    width: width - 20, //左右已经在commentlist中padding了10
  },
  replayAvatar: {
    width: 30,
    height: 30,
    borderRadius: 15
  },
  content: {
    marginTop: 6,
    fontSize: 14,
    color: '#666'
  },


  /*加载更多*/
  loadingMore: {
    marginVertical: 20
  },
  loadingText: {
    color: '#777',
    textAlign: 'center'
  },


  /*评论窗口样式*/
  commitModal: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#fff',
    marginTop: 20,
    paddingLeft: 10,
    paddingRight: 10
  },
  closeIcon: {
    color: '#ee735c',
    alignSelf: 'center',
  },
  commentContent: {
    height: 120,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    paddingHorizontal: 5,
    fontSize: 16,
  },

});

module.exports = Comments